//
//  SmallDecisionsXzpzViewController.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/7/25.
//

#import "SmallDecisionsXzpzViewController.h"
#import <AudioToolbox/AudioToolbox.h>

SmallDecisionsXzpzViewController *xzpzViewController;
CGFloat xzpzTime = 0.03;

@interface SmallDecisionsXzpzViewController ()<CAAnimationDelegate>

@property (nonatomic,strong)UIImageView *xzpzImageView;
@property (nonatomic,strong)UIButton *startAnimationBtn;

@end

@implementation SmallDecisionsXzpzViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        xzpzViewController = self;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"旋转瓶子";
    [self xzpzImageView];
    [self startAnimationBtn];
}

- (UIImageView *)xzpzImageView {
    if(!_xzpzImageView) {
        _xzpzImageView = [[UIImageView alloc] init];
        _xzpzImageView.image = [UIImage imageNamed:@"xzpz_bottle_img"];
        [self.view addSubview:_xzpzImageView];
        [_xzpzImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.centerY.mas_offset(-60);
            make.height.mas_equalTo(300);
            make.width.mas_equalTo(80);
        }];
    }
    return _xzpzImageView;
}

- (UIButton *)startAnimationBtn {
    if (!_startAnimationBtn) {
        _startAnimationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_startAnimationBtn setTitle:@"开始转动" forState:UIControlStateNormal];
        [_startAnimationBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
        _startAnimationBtn.backgroundColor = SmallDecisionsThemeColor;
        _startAnimationBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(22);
        [_startAnimationBtn addTarget:self action:@selector(startAnimationBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _startAnimationBtn.layer.cornerRadius = 30;
        _startAnimationBtn.layer.masksToBounds = YES;
        [self.view addSubview:_startAnimationBtn];
        [_startAnimationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(40);
            make.right.equalTo(self.view).offset(-40);
            make.height.mas_equalTo(60);
            make.top.equalTo(self.xzpzImageView.mas_bottom).offset(80);
        }];
        
    }
    return _startAnimationBtn;
}

- (void)startAnimationBtnAction {
    NSInteger countNum = MAX(2, arc4random() % 20);
    NSInteger targetIndex = arc4random() % 100;
    xzpzTime = 0.03;
    // 开始震动
    AudioServicesAddSystemSoundCompletion(1520, NULL, NULL, vibrationBeerServiceSoundCompleteCallback, NULL);
    AudioServicesPlaySystemSound(1520);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * (countNum - 2) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        xzpzTime = 0.02;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            xzpzTime = 0.04;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                xzpzTime = 0.08;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    xzpzTime = 0.16;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        xzpzTime = 0.3;
                    });
                });
            });
        });
    });
    
    
    CABasicAnimation *xzpzBasicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    xzpzBasicAnimation.toValue = @((M_PI * 2 / countNum) * (countNum - targetIndex) + countNum * 2 * M_PI);
    xzpzBasicAnimation.duration = 0.35 * countNum + 0.35 * (countNum - targetIndex) / (CGFloat)countNum;
    xzpzBasicAnimation.repeatCount = 1.0;
    // 积累
    xzpzBasicAnimation.cumulative = YES;
    xzpzBasicAnimation.fillMode = kCAFillModeForwards;
    xzpzBasicAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    xzpzBasicAnimation.removedOnCompletion = NO;
    xzpzBasicAnimation.autoreverses   = NO;
    xzpzBasicAnimation.delegate       = self;
    [self.xzpzImageView.layer addAnimation:xzpzBasicAnimation forKey:@"transform.rotation.z"];
}


- (void)vibrationBeerAudioServicePlaySystemSound {
    AudioServicesPlaySystemSound(1520);
}

void vibrationBeerServiceSoundCompleteCallback(SystemSoundID sound,void * clientData) {
    if (sound == 1520) {
        [xzpzViewController performSelector:@selector(vibrationBeerAudioServicePlaySystemSound) withObject:nil afterDelay:xzpzTime];
    } else {
        // 注销声音播放完成事件回调函数
        AudioServicesRemoveSystemSoundCompletion(sound);
        // 释放SystemSoundID
        AudioServicesDisposeSystemSoundID(sound);
    }
}

- (void)animationDidStart:(CAAnimation *)anim {
    self.startAnimationBtn.enabled = NO;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    self.startAnimationBtn.enabled = YES;
    // 结束震动
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(vibrationBeerAudioServicePlaySystemSound) object:nil];
    AudioServicesDisposeSystemSoundID(1520);
    AudioServicesRemoveSystemSoundCompletion(1520);
}

@end
